//上传素材
'use strict';
import React,{Component} from 'react';
import styles from '../style/styles';
import Util from '../common/util';
import Icon from 'react-native-vector-icons';
import Toast from '../common/ToastUtil';
import ImagePicker from 'react-native-image-picker';
import * as URLconstant from '../constant/URLconstant';
import MyStroage from '../common/myStroage';
import Login from '../userCenter/login';
import Loading from '../common/loading';
import {
    View,
    Text,
    Image,
    TouchableOpacity,
    Platform,
    TextInput,
    ScrollView
} from 'react-native';
export default class uploadSource extends Component{
    // 构造
      constructor(props) {
        super(props);
        // 初始状态
        this.state = {
            imgNum:1,
            default_image: null,
            is_default_image: false,
            isLoading:false,
            hasAll:false,
            title:''
        };
          this.showUploadImage = this.showUploadImage.bind(this)
          this.uploadImage = this.uploadImage.bind(this)
          this.uploadSuccess = this.uploadSuccess.bind(this)
      }
    isHeader(){
        if (Platform.OS === 'android'){
            return null;
        }else

            return(<View style={{height:20,width:Util.size.width,backgroundColor:"#08cfa8"}}></View>)
    }
    _pop() {
        let that=this;
        that.props.navigator.pop();
    }

    componentDidMount() {
        LOG(this.props.goodsName)
    }

    showUploadImage(){
        let that = this;
        let imgNum = that.state.imgNum;
        let rows;
        let list=[];
        for(let i=0;i<imgNum;i++){
            let imgUri='imgUri'+i;
            let imgUriList = that.state[imgUri]
            let uri;
            if(imgUriList!=null){
                uri=imgUriList['uri'];
            }
            rows=(
                <TouchableOpacity key={i} style={styles.source_img_wrap} onPress={()=>this.uploadImage(i)}>
                    <Icon size={60} color={'#ccc'} name={'ios-add'}/>
                    <Image style={styles.source_img} resizeMode={'cover'} source={{uri:uri, isStatic: true}}/>
                </TouchableOpacity>
            )
            list.push(rows)
        }
        return(
            <View style={styles.source_img_list}>
                {list}
            </View>
        )
    }

    getImageNameByIOS(imageUri) {
        if (imageUri != "") {
            var names = imageUri.split("/");
            return names[names.length - 1];
        }
    }

    uploadImage(i){
        let that = this;
        let imgNum = that.state.imgNum
        const options = {
            quality: 1.0,
            maxWidth: 500,
            maxHeight: 500,
            storageOptions: {
                skipBackup: true
            }
        };
        ImagePicker.showImagePicker(options, (response) => {


            if (response.didCancel) {

            }
            else if (response.error) {

            }
            else if (response.customButton) {
            }
            else {
                let source;
                let imageName;
                let imagePath;

                if (Platform.OS === 'android') {
                    source = response.uri;
                    imagePath = response.path;
                    imageName = response.fileName;

                } else {
                    //{"uri":"/var/mobile/Containers/Data/Application/CC01D123-59FA-4205-8B27-C3181596AA5C/Documents/6131CE7A-FD8C-44DB-B9B9-82C322294B88.jpg","isStatic":true}
                    //file:///Users/dev/Library/Developer/CoreSimulator/Devices/DA8C975D-D476-462B-B387-D43FBC55C333/data/Containers/Data/Application/6231A942-22AA-40DC-A303-898EDE2C7533/Documents/2E98BCB0-8A9E-43FF-88E6-E7BE2094EE62.jpg
                    source = response.uri.replace('file://', '');
                    imagePath = response.uri.replace('file://', '');
                    imageName = that.getImageNameByIOS(response.uri);
                }

                let imageinfo = [];
                imageinfo['uri'] = source;//这个是给React-native Image组件显示图片用得地址;
                imageinfo['imageName'] = imageName;//图片名称
                imageinfo['imagePath'] = imagePath;//图片在本机的路径.
                let imgUri = 'imgUri'+i;
                that.setState({
                    [imgUri]: imageinfo,
                    default_image: imageinfo,
                });


                    if(imgNum<9 && i==imgNum-1){
                    that.setState({
                        imgNum:imgNum+1
                    })
                }else if(imgNum==9){
                    this.setState({
                        hasAll:true
                    })
                }
            }
        });


    }

    async publish(){
        try{
            let that = this;
            let userInfoDate = await MyStroage.getStorageAllDataForKey('userinfo')
            // LOG('KEY11111======' + JSON.stringify(userInfoDate));
            if (userInfoDate == null) {
                that.props.navigator.push(
                    {
                        component: Login,
                        passProps: {
                            navigator: this.props.navigator,
                            onLoginSuccess: this.onLoginSuccess
                        }
                    }
                );
            }else{
                if(that.state.title==''){
                    Toast.show('请说说您的心得');return false;
                }
                if(that.state.imgNum==1){
                    Toast.show('请先上传图片');return false;
                }
                this.setState({
                    isLoading:true
                })
                let hasAll = that.state.hasAll;
                let imgNum;
                if(hasAll==false){
                    imgNum=parseInt(that.state.imgNum)-1
                }else{
                    imgNum=9
                }
                let title = this.state.title;
                let das = new FormData();
                let default_image;
                for(let i = 0;i<imgNum;i++){
                    let imgUri='imgUri'+i;
                    let imgUriList = that.state[imgUri];
                    default_image = {
                        uri: imgUriList['uri'],
                        type: "multipart/form-data",
                        name: imgUriList['imageName']
                    };
                    das.append('image_'+i,default_image);
                }
                let url = URLconstant.UPLOAD_MATERIAL;
                das.append('gid',that.props.goodsId);
                das.append('image_num',imgNum);
                das.append('title',title);
                das.append("signme", 1);
                das.append("local", ISLOCAL);
                das.append('user_id',userInfoDate.data.user_id)
                LOG('das====='+JSON.stringify(das))
                Util.post2(url,das,this.uploadSuccess,this.errorCallback)
            }

        }catch(e){

        }

    }


    uploadSuccess(datas){
        this.setState({
            isLoading:false
        })
        if(datas.status==0){
            Toast.show(datas.msg);
            this.props.navigator.pop();
            this.props.oncallback()
        }else{
            Toast.show(datas.msg)
        }
    }

    errorCallback(error){
        LOG('error====='+error)
    }

    render(){
        return(
            <View style={{flex:1}}>
                {this.isHeader()}
                <View style={styles.header}>
                    <TouchableOpacity style={styles.header_back} onPress={()=>this._pop()}>
                        <Icon name={'ios-arrow-back'} size={30} color="#fff" />
                    </TouchableOpacity>
                    <Text style={styles.header_title}>文案发布</Text>
                    <TouchableOpacity style={styles.head_setting} onPress={()=>this.publish()}>
                        <Text style={{fontSize:12,color:"#fff"}}>发布</Text>
                    </TouchableOpacity>
                </View>
                <ScrollView style={styles.bg_scrollview}>
                    <View style={styles.input_wrap}>
                        <TextInput
                            placeholder="说说你的心得"
                            multiline={true}
                            maxLength={120}
                            style={styles.source_input}
                            onChangeText={(text)=>this.setState({title:text})}
                            underlineColorAndroid={'transparent'}
                        />
                        <Text style={styles.input_max}>120字</Text>
                    </View>
                    {this.showUploadImage()}
                    <View style={styles.source_name_wrap}>
                        <Text style={styles.source_name}>{this.props.goodsName}</Text>
                    </View>
                </ScrollView>
                <Loading isLoading={this.state.isLoading}/>
            </View>
        )
    }
}